package com.asm;

import com.asm.handler.*;
import com.asm.message.GroupQuitRequestMessage;
import com.asm.protocol.MessageCodecSharable;
import com.asm.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * 聊天--服务端
 */
@Slf4j
public class chatServer {
    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        // 局部变量//可共享的
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //可共享的
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        //可共享的
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupCreatRequestMessageHandler GROUP_CREAT_HANDLER = new GroupCreatRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupMemberRequestMessageHandler GROUP_MEMBER_HANDLER = new GroupMemberRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        Quit_ConnectHandler QUIT_HANDLER = new Quit_ConnectHandler();
        try {
            ServerBootstrap bs = new ServerBootstrap();
            bs.channel(NioServerSocketChannel.class);
            bs.group(boss, worker);
            bs.childOption(ChannelOption.TCP_NODELAY,true);
            bs.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    /**@ClassName IdleStateHandler
                     * 用来判断是不是 读空闲时间过长，或写空闲时间过长
                    如果5秒没有收到channel的数据，
                    会触发一个 IdleState.READER_IDLE事件*/
                    ch.pipeline().addLast(new IdleStateHandler(10, 0, 0));
                    //ChannelDuplexHandler可以同时作为出入站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //用来触发特殊事件

                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            //如果两者相等，触发了读空闲事件
                            if (event.state() == IdleState.READER_IDLE) {
                               log.debug("已经10秒没有读到数据了");
                                ctx.channel().close();
                            }
                            super.userEventTriggered(ctx, evt);
                        }
                    });

                    // 帧解码器 【与自定义编解码器 MessageCodecSharable一起配置参数】只有入站
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    // 日志
                    ch.pipeline().addLast(LOGGING_HANDLER);

                    // 出站入站的 自定义编解码器 【 解析消息类型 】
                    ch.pipeline().addLast(MESSAGE_CODEC);

                    // simple处理器 【针对性的对登录进行处理】 【流水线 会向上执行出站Handler,  到 ProcotolFrameDecoder(入站停止)】
                    //登录处理器
                    ch.pipeline().addLast(LOGIN_HANDLER);
                    //单聊处理器
                    ch.pipeline().addLast(CHAT_HANDLER);
                    //创建群聊处理器
                    ch.pipeline().addLast(GROUP_CREAT_HANDLER);
                    //加入群聊
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                    //获取群成员信息
                    ch.pipeline().addLast(GROUP_MEMBER_HANDLER);
                    //退出群聊
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                    //群聊处理器
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                    //--断开连接---处理器
                    ch.pipeline().addLast(QUIT_HANDLER);


                }
            });

            ChannelFuture channelFuture = bs.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {

            log.error("server error", e);

        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }


}
